public class TournamentSelection implements Selection {
	double mutaionProb, crossoverProb;
	
	public TournamentSelection(double mutaionProb, double crossoverProb) {
		this.mutaionProb = mutaionProb;
		this.crossoverProb = crossoverProb;
	}

	private boolean testProb(double prob) { // task9 1)
		boolean ans;
		if (prob > Math.random()) {
			ans = true;
		}else{
			 ans = false;
		}
		return ans;
	}

	private Individual select(Individual[] pop) { // task9 2)
		int firstContender = (int) ((pop.length)* Math.random());
		int secondContender = (int) ((pop.length)* Math.random()); // why can't I just declare it
		/* now here I would like to take to account a case that 
		 * the two contenders are in fact the same one and try again
		 */
		/*boolean notSame=true;
		for(int i = 1;notSame & i < pop.length;i = i+1){
			secondContender = (int) ((pop.length)* Math.random());
			if (firstContender != secondContender) notSame=false;
		}*/
		Individual choosen;
		if (firstContender < secondContender) {
			choosen = pop[firstContender].copyOf();
		} else {
			choosen = pop[secondContender].copyOf();
		}
		return choosen;
	}

	private Individual doCrossover(Individual[] pop) { //task9 3)
		Individual child;
		if (testProb(crossoverProb)) {
			Individual mother = select(pop);
			Individual father = select(pop);
			child = mother.crossover(father);
		}else{
			child = select(pop);
		}
		return child;
	}

	private Individual mutate(Individual other) { //task9 4)
		Individual ans = other.copyOf();
		if (testProb(mutaionProb)) ans = ans.mutate();
		return ans;
	}

	public Individual reproduce(Individual[] pop) {
		return mutate(doCrossover(pop));
	}
}
